import React from 'react';
import {Table, Card, Divider, Form, Input, Row, Col, Button, Modal, message, Icon, Tag} from 'antd';
import {connect} from 'dva';
import {ColumnProps, TableProps} from 'antd/es/table';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {FormComponentProps} from 'antd/es/form';
import {ModelState} from './model';
import {Dispatch} from 'redux';
import router from "umi/router";

interface IProps extends FormComponentProps {
  menusList: ModelState;
  loading: boolean;
  dispatch: Dispatch<any>;
}

interface IStates {
  selectedRowKeys: any[];
  formValues: object;
  saveModalVisible: boolean;
}

class Index extends React.Component<IProps, IStates> {
  state: IStates = {
    selectedRowKeys: [],
    formValues: {},
    saveModalVisible: false,
  };

  tableColumns: ColumnProps<{}>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '路由',
      dataIndex: 'path',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      render: (text: string, record: any) => {
        console.info("!!!!!!!!!!!!!!!!!!!!!!!!");
        console.info(text);
        text = text.replace(/(^\s*)|(\s*$)/g, "");
        if (text.length === 0) {
          return '';
        }
        return (
          <Icon type={text}/>
        );
      },
    },
    {
      title: '显示',
      dataIndex: 'visible',
      render: (text: number, record: any) => {
        return !!text ? <Tag color="#108ee9">是</Tag> : <Tag color="#f50">否</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
    },
    {
      title: '操作',
      render: (text: any, record: any) => {
        return (
          <>
            <a
              onClick={() => {
                const url = `/account/menu/save/${record.id}`;
                router.push(url);
              }}
            >
              编辑
            </a>
            <Divider type="vertical"/>
            <a onClick={() => {
              this.batchDelete(record.id);
            }}>删除</a>
          </>
        );
      },
    },
  ];


  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'menusList/fetch',
    });
  }

  tableChange: TableProps<{}>['onChange'] = (pagination, filters, sorter, extra) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;
    const params = {
      ...formValues,
      ...pagination
    };

    dispatch({
      type: 'menusList/fetch',
      payload: params
    });
  };

  searchSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const {form, dispatch} = this.props;
    form.validateFields((err, fieldsValue) => {
      const values = {...fieldsValue};

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'menusList/fetch',
        payload: values,
      });
    });
  };

  resetFrom = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'menusList/fetch',
      payload: {},
    });
  };


  //批量删除or单个删除
  batchDelete = (id = null) => {

    let ids: any[] = [];
    let title: string;
    if (!id) {
      ids = this.state.selectedRowKeys;
      title = '批量删除菜单';
    } else {
      ids = [id];
      title = '删除菜单';
    }

    const {dispatch} = this.props;
    Modal.confirm({
      title: title,
      content: '您确认要删除所选菜单吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (ids.length === 0) {
          message.warning('请先选择你要删除的选项');
          return;
        }
        dispatch({
          type: 'menusList/batchDelete',
          payload: {ids: ids}
        });
      }
    });
  };


  render() {
    const {selectedRowKeys} = this.state;
    const {form, menusList: {data}, loading} = this.props;
    console.log('data');
    console.log(data);

    const getFieldDecorator = form.getFieldDecorator;

    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys: any[], selectedRows: any[]) => {
        this.setState({
          selectedRowKeys: selectedRowKeys,
        });
      }
    };

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.searchSubmit}>
            <Row>
              <Col span={10}>
                <Button
                  type="primary"
                  onClick={() => {
                    const url = `/account/menu/save/0`;
                    router.push(url);
                  }}
                >
                  新增
                </Button>
                <Button type="danger" style={{marginLeft: 10}} onClick={() => {
                  this.batchDelete(null)
                }}>
                  删除
                </Button>
              </Col>
              <Col span={14}>
                <div style={{float: 'right', display: "none"}}>
                  <Form.Item>
                    {getFieldDecorator('keyword', {})(
                      <Input placeholder="请输入角色标题" {...{}} style={{width: 250}}/>,
                    )}
                  </Form.Item>
                  <Button type="primary" style={{marginTop: 4}} htmlType="submit">
                    查询
                  </Button>
                  <Button type="dashed" style={{margin: '4px 0 0 5px'}} onClick={this.resetFrom}>
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
          <Divider/>
          <Table
            loading={loading}
            rowKey="id"
            columns={this.tableColumns}
            dataSource={data.list}
            pagination={data.pagination}
            rowSelection={rowSelection}
            onChange={this.tableChange}
            {...{}}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<IProps>()(
  connect(
    ({
       menusList,
       loading,
     }: {
      menusList: ModelState;
      loading: {
        models: {
          [key: string]: boolean;
        };
      };
    }) => ({
      menusList,
      loading: loading.models.menusList,
    }),
  )(Index),
);
